<?php

namespace App\Http\Service;
use App\Repositories\CommonRepository;

class CommonService{
    protected $common_repository;

    public function __construct()
    {
        $this->common_repository = new CommonRepository();
    }
    /**zwp
     * 获取产品分类
     * @param type $name
     * @return array
     */
    public function getCategoryByName($name){
        $ids = $this->common_repository->getId($name);
        if(!is_array($ids)){
            $ids[] = ["id"=>$ids];
        }
        $data =  $this->common_repository->getCategoryById($ids);
        if(!$data){
            return null;
        }
        $data = $data->toArray();
        //var_dump($data);exit();
        $ids = [];
        foreach ($data as $val){
            $id = $val["pid"];
            if(!in_array($id, $ids)){
                $ids[] = $id;
            }
        }
        
        $data = $this->common_repository->getCategoryByIds(["id","name"],$ids);
        if(!$data){
            return null;
        }
        
        return $data->toArray();
    }
    /**zwp
     * 获取地区
     * @return array
     */
    public function getArea(){
        $data = $this->common_repository->getAreaNameAndId();
        array_splice($data, 0,2);
        return $data;
    }
    public function getJobs(){
        $data = $this->common_repository->getJobs();
        if(!$data){
            return null;
        }
        $data = $data->toArray();
        $data = $this->doJobsRelation($data);
        return $data;
    }
    public function doJobsRelation($data){
        foreach ($data as &$val){
            $name = "";
            if($val["pid"]==0){
                $name = $val["name"];
                $val["relationName"] = $name;
            }else{
                $id = $val["pid"];
                $name = $val["name"];
                while($id!=0){
                    $res = $this->findFather($data,$id);
                    if($res!=null){
                        $id = $res["id"];
                    }else{
                        $id = 0;
                    }
                    $name = $res["name"]."-".$name;
                }
                $val["relationName"] = $name;
                
            }
        }
        return $data;
    }
    public function findFather($data,$id){
        $name = "";
        foreach ($data as $value){
            if($id == $value["id"]){
                $name = $name.$value["name"];
                $id = $value["pid"];
                return ["name"=>$name,"id"=>$id];
            }
        }
        return null;
    }
}